/*
 * Permission.java
 *
 * Created on August 1, 2007, 10:03 AM
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package org.atomojo.auth.service.db;

import java.sql.SQLException;
import java.util.UUID;
import org.infoset.xml.Element;
import org.infoset.xml.ItemConstructor;
import org.infoset.xml.ItemDestination;
import org.infoset.xml.XMLException;
import org.milowski.db.DBConnection;
import org.milowski.db.DBObject;

/**
 *
 * @author alex
 */
public class Permission extends DBObject<AuthDB>  implements XMLObject
{

   String name;
   UUID uuid;
   
   /** Creates a new instance of Permission */
   public Permission(AuthDB db,int id,String name,UUID uuid)
   {
      super(db,id);
      this.name = name;
      this.uuid = uuid;
   }
   
   public void delete() 
      throws SQLException
   {
      DBConnection connection = db.getConnection();
      try {
         connection.deleteById(AuthDB.DELETE_ROLE_PERMISSIONS_BY_PERMISSION, id);
         connection.deleteById(AuthDB.DELETE_PERMISSION, id);
         db.realmGroupCaches.clear();
         db.roleCache.clear();
         db.permissionCache.remove(id);
      } finally {
         db.release(connection);
      }
   }

   public String getName()
   {
      return name;
   }

   public UUID getUUID()
   {
      return uuid;
   }
   
   public boolean equals(Object obj) {
      return obj instanceof Permission && ((Permission)obj).getUUID().equals(uuid);
   }
   
   public void generate(ItemConstructor constructor,ItemDestination dest)
      throws XMLException
   {
      Element top = constructor.createElement(XML.PERMISSION_NAME);
      top.setAttributeValue("id",uuid.toString());
      top.setAttributeValue("name",name);
      dest.send(top);
      dest.send(constructor.createElementEnd(XML.PERMISSION_NAME));
   }
   public void generate(ItemConstructor constructor,ItemDestination dest,boolean contents)
      throws XMLException
   {
      generate(constructor,dest);
   }
}
